package edu.ynu.se.xiecheng.achitectureclass.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.ynu.se.xiecheng.achitectureclass.entity.Order;
import edu.ynu.se.xiecheng.achitectureclass.entity.Shop;
import edu.ynu.se.xiecheng.achitectureclass.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.entity.vo.OrderListVo;
import edu.ynu.se.xiecheng.achitectureclass.entity.vo.OrderVO;
import edu.ynu.se.xiecheng.achitectureclass.entity.vo.Result;
import edu.ynu.se.xiecheng.achitectureclass.mapper.OrderMapper;
import edu.ynu.se.xiecheng.achitectureclass.mapper.ShopMapper;
import edu.ynu.se.xiecheng.achitectureclass.mapper.UserMapper;
import edu.ynu.se.xiecheng.achitectureclass.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author laruui
 * @since 2023-12-07
 */
@Slf4j
@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ShopMapper shopMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public Result pageOrder(int current, int size, String userId) {
        try {
            Page<OrderListVo> orderPage = new Page<>(current, size);
            List<Order> filterOrderList = filterOrderData(userId);
            List<OrderListVo> orderListVoList = heBin(filterOrderList);
            int count = orderListVoList.size();
            List<OrderListVo> pageList = new ArrayList<>();
            //计算当前页第一条数据的下标
            int currId = current > 1 ? (current - 1) * size : 0;
            for (int i = 0; i < size && i < count - currId; i++) {
                pageList.add(orderListVoList.get(currId + i));
            }
            orderPage.setSize(size);
            orderPage.setCurrent(current);
            orderPage.setTotal(count);
            //计算分页总页数
            orderPage.setPages(count % 10 == 0 ? count / 10 : count / 10 + 1);
            orderPage.setRecords(pageList);
            orderPage.getRecords().forEach(System.out::println);
            return Result.builder().code(200).message("查询成功！").data(orderPage).build();
        } catch (Exception e) {
            log.info("出现异常！");
            return Result.builder().code(500).message("系统故障").build();
        }
    }

    public List<OrderListVo> heBin(List<Order> filterOrderList) {
        Map<String, OrderListVo> orderListVoMap = new HashMap<>();

        for (Order order : filterOrderList) {
            String sn = order.getSn();
            if (orderListVoMap.containsKey(sn)) {
                OrderListVo vo = orderListVoMap.get(sn);
                vo.getShopItem().add(order.getItemName());
                vo.getItemPrice().add(String.valueOf(order.getItemPrice()));
                vo.getItemNum().add(String.valueOf(order.getItemNumber()));
                orderListVoMap.put(sn, vo);
            } else {
                OrderListVo orderListVo = new OrderListVo();
                orderListVo.setSn(sn);
                orderListVo.setStatus(order.getStatus());
                orderListVo.setShopName(order.getShopName());
                orderListVo.setTotalPrice(order.getTotal());
                orderListVo.getShopItem().add(order.getItemName());
                orderListVo.getItemPrice().add(String.valueOf(order.getItemPrice()));
                orderListVo.getItemNum().add(String.valueOf(order.getItemNumber()));
                orderListVoMap.put(sn, orderListVo);
            }
        }
        return new ArrayList<>(orderListVoMap.values());
    }

    /**
     * 过滤合并同一商品
     *
     * @return 处理完成的数据
     */
    public List<Order> filterOrderData(String userId) {
        User user = userMapper.selectById(userId);
        List<Order> orderList = new ArrayList<>(16);
        if ("customer".equals(user.getFlag())) {
            // 查询所有的订单商品
            LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLambdaQueryWrapper.eq(Order::getUserId, userId);
            orderList = orderMapper.selectList(orderLambdaQueryWrapper);
        } else if ("business".equals(user.getFlag())) {
            LambdaQueryWrapper<Shop> shopLambdaQueryWrapper = new LambdaQueryWrapper<>();
            shopLambdaQueryWrapper.eq(Shop::getUserId, userId);
            List<Shop> shopList = shopMapper.selectList(shopLambdaQueryWrapper);
            // 商家所有的店铺
            List<String> shopIdList = shopList.stream().map(Shop::getId).collect(Collectors.toList());
            // 查询所有的订单
            // TODO
            LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLambdaQueryWrapper.eq(Order::getStatus, "已支付");
            List<Order> allOrderList = orderMapper.selectList(orderLambdaQueryWrapper);
            orderList = new ArrayList<>();
            for (Order order : allOrderList) {
                if (shopIdList.contains(order.getShopId())) {
                    orderList.add(order);
                }
            }
        }
        Map<String, Order> orderMap = new HashMap<>();
        List<Order> filterOrderList = new ArrayList<>(16);
        // 合并
        for (Order o : orderList) {
            if (orderMap.containsKey(o.getItemId())) {
                Order order = orderMap.get(o.getItemId());
                order.setItemNumber(order.getItemNumber() + o.getItemNumber());
                orderMap.put(o.getItemId(), order);
            } else {
                orderMap.put(o.getItemId(), o);
            }
        }
        // 添加
        for (Map.Entry<String, Order> entry : orderMap.entrySet()) {
            filterOrderList.add(entry.getValue());
        }
        return filterOrderList;
    }

    @Override
    public Result addOrder(List<OrderVO> orderVOList, float totalPrice) {
        try {
            orderVOList.forEach(o -> o.setTotalPrice(totalPrice));
            insertOrderBySN(orderVOList);
            return Result.builder().code(200).build();
        } catch (Exception e) {
            log.info(e.getMessage());
            return Result.builder().code(500).message("系统故障").build();
        }
    }

    @Override
    public Result removeOrder(String sn) {
        try {
            LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLambdaQueryWrapper.eq(Order::getSn, sn);
            int row = orderMapper.delete(orderLambdaQueryWrapper);
            return Result.builder().code(200).message("订单取消成功！").data(String.valueOf(row)).build();
        } catch (Exception e) {
            log.info(e.getMessage());
            return Result.builder().code(500).message("系统故障").build();
        }
    }

    @Override
    public Result paymentOrder(String sn) {
        try {
            LambdaUpdateWrapper<Order> orderLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            orderLambdaUpdateWrapper.eq(Order::getSn, sn)
                    .set(Order::getStatus, "已支付");
            int row = orderMapper.update(null, orderLambdaUpdateWrapper);
            return Result.builder().code(200).message("订单已支付！").data(String.valueOf(row)).build();
        } catch (Exception e) {
            log.info(e.getMessage());
            return Result.builder().code(500).message("系统故障").build();
        }
    }

    @Override
    public Result enterOrder(String sn) {
        try {
            LambdaUpdateWrapper<Order> orderLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            orderLambdaUpdateWrapper.eq(Order::getSn, sn)
                    .set(Order::getStatus, "已确认")
                    .set(Order::getIsDelete, "1");
            int row = orderMapper.update(null, orderLambdaUpdateWrapper);
            return Result.builder().code(200).message("支付订单已确认！").data(String.valueOf(row)).build();
        } catch (Exception e) {
            log.info(e.getMessage());
            return Result.builder().code(500).message("系统故障").build();
        }
    }

    @Override
    public Result returnAmountOrder(String sn) {
        try {
            LambdaUpdateWrapper<Order> orderLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            orderLambdaUpdateWrapper.eq(Order::getSn, sn)
                    .set(Order::getStatus, "已退款")
                    .set(Order::getIsDelete, "1");
            int row = orderMapper.update(null, orderLambdaUpdateWrapper);
            return Result.builder().code(200).message("支付订单已退款！").data(String.valueOf(row)).build();
        } catch (Exception e) {
            log.info(e.getMessage());
            return Result.builder().code(500).message("系统故障").build();
        }
    }

    /**
     * 同一门店，结算至同一订单
     *
     * @param orderVOList 后续商品
     */
    public void insertOrderBySN(List<OrderVO> orderVOList) {
        // 获取时间戳流水号
        String sn = String.valueOf(System.currentTimeMillis());
        // 获取门店id,因为同一门店结算商品应为一个订单
        String shopId = orderVOList.get(0).getShopId();
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(Order::getShopId, shopId);
        // 获取订单库之前未支付门店订单
        List<Order> OrderListed = orderMapper.selectList(orderLambdaQueryWrapper);
        Order order = null;
        if (!OrderListed.isEmpty()) {
            // 获取该门店之前订单流水号
            String nowEdSn = OrderListed.get(0).getSn();
            // 获取之前订单总价
            float total = Float.parseFloat(OrderListed.get(0).getTotal());
            // 获取现在的订单总价
            float totalPrice = orderVOList.get(0).getTotalPrice();
            // 将两段新的商品总价相加，得到新的最新总价
            float finalTotalPrice = total + totalPrice;
            OrderListed.forEach(o -> o.setTotal(String.valueOf(finalTotalPrice)));
            for (OrderVO orderVO : orderVOList) {
                order = new Order();
                order.setSn(nowEdSn);
                order.setItemId(orderVO.getId());
                order.setItemImage(orderVO.getImage());
                order.setItemName(orderVO.getName());
                order.setItemNumber(orderVO.getNum());
                order.setItemPrice(BigDecimal.valueOf(orderVO.getPrice()));
                order.setShopId(orderVO.getShopId());
                order.setUserId(orderVO.getUserId());
                order.setTotal(String.valueOf(finalTotalPrice));
                order.setStatus("未支付");
                String shopName = shopMapper.selectOne(new LambdaQueryWrapper<Shop>().eq(Shop::getId, orderVO.getShopId())).getName();
                order.setShopName(shopName);
                orderMapper.insert(order);
            }
            this.saveOrUpdateBatch(OrderListed);
        } else {
            // 正常插入第一次的订单
            for (OrderVO orderVO : orderVOList) {
                order = new Order();
                order.setSn(sn);
                order.setItemId(orderVO.getId());
                order.setItemImage(orderVO.getImage());
                order.setItemName(orderVO.getName());
                order.setItemNumber(orderVO.getNum());
                order.setItemPrice(BigDecimal.valueOf(orderVO.getPrice()));
                order.setShopId(orderVO.getShopId());
                order.setUserId(orderVO.getUserId());
                order.setTotal(String.valueOf(orderVO.getTotalPrice()));
                order.setStatus("未支付");
                String shopName = shopMapper.selectOne(new LambdaQueryWrapper<Shop>().eq(Shop::getId, orderVO.getShopId())).getName();
                order.setShopName(shopName);
                orderMapper.insert(order);
            }
        }
    }
}
